package com.zuoqi.common.utils;


import com.zuoqi.easywork.userManage.model.TcResc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangqiang on 2015/5/22.
 */
public class TreeHelper {

    public static List<TreeNode> convertMenuTree(List<TcResc> allList) {
        return convertMenuTree(allList,null,null);
    }

    public static List<TreeNode> convertMenuTree(List<TcResc> allList, List<String> checkedList) {
        return convertMenuTree(allList,checkedList,null);
    }

    public static List<TreeNode> convertMenuTree(List<TcResc> allList, List<String> checkedList, List<String> chkDisabledList) {
        List<TreeNode> nodes = null;
        if (allList != null) {
            nodes = new ArrayList<TreeNode>();
            for (TcResc resource : allList) {
                TreeNode node = convertMenuTreeNode(resource, checkedList,chkDisabledList);
                if (node != null) {
                    nodes.add(node);
                }
            }
        }
        return convertList2tree(nodes);
    }

    private static TreeNode convertMenuTreeNode(TcResc resource,List<String> checkedList, List<String> chkDisabledList) {
        TreeNode node = null;
        if (resource != null) {
            node = new TreeNode();
            node.setId(resource.getRescId());
            node.setChecked((null != checkedList && checkedList.contains(resource.getRescId()))?true:false);
            node.setChkDisabled((null != chkDisabledList && chkDisabledList.contains(resource.getRescId()))?true:false);
            node.setText(resource.getRescName());
            node.setState(resource.getRescType());
            node.setTarget("");
            node.setPid("");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("url", resource.getRescUrl());
            map.put("icon", "");
            node.setAttributes(map);
        }
        return node;
    }
    
    private static List<TreeNode> convertList2tree(List<TreeNode> list) {
        List<TreeNode> nodeList = new ArrayList<TreeNode>();
        for(TreeNode node1 : list){
            boolean mark = false;
            for(TreeNode node2 : list){
                if(node1.getPid()!= null && node1.getPid().equals(node2.getId())){
                    mark = true;
                    if(node2.getChildren() == null)
                        node2.setChildren(new ArrayList<TreeNode>());
                    node2.getChildren().add(node1);
                    break;
                }
            }
            if(!mark){
                nodeList.add(node1);
            }
        }
        return nodeList;
    }
}
